<template>
    <div class="my-new-finance">
        <v-dialog
            :title="isAdd ? '新增' : '编辑'"
            :show.sync="dialogVisible"
            width="1200px"
            @beforeClose="beforeClose"
            :close-on-click-modal="false">
            <div class="card-box">
                <div class="card-title">工程信息</div>
                <el-form ref="information" :model="projectForm.information" class="form-wrap" size="small" :rules="information_rules" label-position="top">
                    <el-form-item label="工程名称" prop="projectName">
                        <el-input readonly suffix-icon="el-icon-search" v-model="projectForm.information.projectName" maxlength="100" placeholder="请输入工程名称" @click.native="handleClickProjectName"></el-input>
                    </el-form-item>
                    <el-form-item label="工程地址" prop="projectAddress">
                        <el-input readonly v-model="projectForm.information.projectAddress" maxlength="100" placeholder="请输入工程地址"></el-input>
                    </el-form-item>
                    <el-form-item label="工程类型" prop="projectType">
                        <el-input readonly v-model="projectForm.information.projectType" maxlength="100" placeholder="请输入工程类型"></el-input>
                    </el-form-item>
                </el-form>
                <div class="card-title">设计招标信息</div>
                <el-form ref="designTender" :model="projectForm.designTender" class="form-wrap" size="small" :rules="designTender_rules" label-position="top">
                    <el-form-item label="中标文号" prop="designDocument">
                        <el-input v-model="projectForm.designTender.designDocument" maxlength="50" placeholder="请输入文号"></el-input>
                    </el-form-item>
                    <el-form-item label="中标单位" prop="designUnit">
                        <el-input v-model="projectForm.designTender.designUnit" maxlength="50" placeholder="请输入中标单位"></el-input>
                    </el-form-item>
                    <el-form-item label="金额(元)" prop="designAmount">
                        <el-input v-model="projectForm.designTender.designAmount" maxlength="18" placeholder="请输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="中标日期" prop="designDate">
                        <el-date-picker
                            v-model="projectForm.designTender.designDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd"
                            placeholder="请选择中标日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-form>
                <div class="card-title">监理招标信息</div>
                <el-form ref="supervision" :model="projectForm.supervision" class="form-wrap" size="small" :rules="supervision_rules" label-position="top">
                    <el-form-item label="中标文号" prop="supervisorDocument">
                        <el-input v-model="projectForm.supervision.supervisorDocument" maxlength="50" placeholder="请输入文号"></el-input>
                    </el-form-item>
                    <el-form-item label="中标单位" prop="supervisorUnit">
                        <el-input v-model="projectForm.supervision.supervisorUnit" maxlength="50" placeholder="请输入中标单位"></el-input>
                    </el-form-item>
                    <el-form-item label="金额(元)" prop="supervisorAmount">
                        <el-input v-model="projectForm.supervision.supervisorAmount" maxlength="18" placeholder="请输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="中标日期" prop="supervisorDate">
                        <el-date-picker
                            v-model="projectForm.supervision.supervisorDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd"
                            placeholder="请选择中标日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-form>
                <div class="card-title">造价咨询信息</div>
                <el-form ref="cost" :model="projectForm.cost" class="form-wrap" size="small" :rules="cost_rules" label-position="top">
                    <el-form-item label="中标文号" prop="costDocument">
                        <el-input v-model="projectForm.cost.costDocument" maxlength="50" placeholder="请输入文号"></el-input>
                    </el-form-item>
                    <el-form-item label="中标单位" prop="costUnit">
                        <el-input v-model="projectForm.cost.costUnit" maxlength="50" placeholder="请输入中标单位"></el-input>
                    </el-form-item>
                    <el-form-item label="金额(元)" prop="costAmount">
                        <el-input v-model="projectForm.cost.costAmount" maxlength="18" placeholder="请输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="中标日期" prop="costDate">
                        <el-date-picker
                            v-model="projectForm.cost.costDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd"
                            placeholder="请选择中标日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-form>
                <div class="card-title">招标代理信息</div>
                <el-form ref="tenderAgent" :model="projectForm.tenderAgent" class="form-wrap" size="small" :rules="tenderAgent_rules" label-position="top">
                    <el-form-item label="中标文号" prop="agentDocument">
                        <el-input v-model="projectForm.tenderAgent.agentDocument" maxlength="50" placeholder="请输入文号"></el-input>
                    </el-form-item>
                    <el-form-item label="中标单位" prop="agentUnit">
                        <el-input v-model="projectForm.tenderAgent.agentUnit" maxlength="50" placeholder="请输入中标单位"></el-input>
                    </el-form-item>
                    <el-form-item label="金额(元)" prop="agentAmount">
                        <el-input v-model="projectForm.tenderAgent.agentAmount" maxlength="18" placeholder="请输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="中标日期" prop="agentDate">
                        <el-date-picker
                            v-model="projectForm.tenderAgent.agentDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd"
                            placeholder="请选择中标日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-form>
                <div class="card-title">施工招标信息</div>
                <el-form ref="construction" :model="projectForm.construction" class="form-wrap" size="small" :rules="construction_rules" label-position="top">
                    <el-form-item label="中标文号" prop="constructionDocument">
                        <el-input v-model="projectForm.construction.constructionDocument" maxlength="50" placeholder="请输入文号"></el-input>
                    </el-form-item>
                    <el-form-item label="中标单位" prop="constructionUnit">
                        <el-input v-model="projectForm.construction.constructionUnit" maxlength="50" placeholder="请输入中标单位"></el-input>
                    </el-form-item>
                    <el-form-item label="金额(元)" prop="constructionAmount">
                        <el-input v-model="projectForm.construction.constructionAmount" maxlength="18" placeholder="请输入金额"></el-input>
                    </el-form-item>
                    <el-form-item label="中标日期" prop="constructionDate">
                        <el-date-picker
                            v-model="projectForm.construction.constructionDate"
                            type="date"
                            value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd"
                            placeholder="请选择中标日期"
                        ></el-date-picker>
                    </el-form-item>
                </el-form>
                <div class="card-title">附件</div>
                <div class="handling-opinions">
                    <v-upload
                        ref="tenderInfoUpload"
                        :busId="projectForm.information.projectTenderId"
                        modelType="tenderInfo"
                        @onSuccess="onSuccess"
                        isShowFileList
                        :isView="false"
                        multiple
                        v-model="fileList"/>
                </div>
            </div>
            <span slot="foot">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button v-throttle="[commit]">保 存</el-button>
          </span>
        </v-dialog>
<!--        工程弹框-->
        <choose-dialog ref="chooseDialog" v-bind="chooseDialogAttrs" @chooseData="handleClickAdd" />
    </div>
</template>

<script>
    import BaseLoad from '@/assets/vue-mixin/BaseLoad'
    import { doubleValidate} from '~/utils/validate.js'
    import {save, update, get, validateCode} from '../api/tenderInfo'
    export default {
        name: "edit-data",
        created() {
            this.projectTypes = this.getDict('epc_project_type')
        },
        mixins: [BaseLoad],
        data() {
            let validateSymbol = (rule, value, callback) => {
                if (!value) {
                    callback()
                }
                this.validateOnly(rule, value, callback)
            };
            return {
                dialogVisible: false,
                isAdd: true,
                symbolType: '',
                projectForm: {
                    information: {
                        projectId: '',
                        projectSetupId: '',
                        projectTenderId: '',
                        projectName: '',
                        projectAddress: '',
                        projectType: ''
                    },
                    designTender: {
                        designDocument: '',
                        designUnit: '',
                        designAmount: '',
                        designDate: ''
                    },
                    supervision: {
                        supervisorDocument: '',
                        supervisorUnit: '',
                        supervisorAmount: '',
                        supervisorDate: ''
                    },
                    cost: {
                        costDocument: '',
                        costUnit: '',
                        costAmount: '',
                        costDate: ''
                    },
                    tenderAgent: {
                        agentDocument: '',
                        agentUnit: '',
                        agentAmount: '',
                        agentDate: ''
                    },
                    construction: {
                        constructionDocument: '',
                        constructionUnit: '',
                        constructionAmount: '',
                        constructionDate: ''
                    }
                },
                registrationForm: {},
                projectTypes: [],
                fileList: [],
                // 选择弹窗属性数据
                chooseDialogAttrs: {},
                information_rules: {
                    projectName: [{required: true, message: '请输入工程名称', trigger: 'change'}],
                    projectAddress: [{required: true, message: '请输入工程地址', trigger: 'blur'}],
                    projectType: [{required: true, message: '请选择工程类型', trigger: 'blur'}]
                },
                designTender_rules: {
                    designAmount: [{required: false, message: '请输入金额', trigger: 'blur'},
                        { validator: doubleValidate, trigger: "blur"}],
                    designDocument: [{required: false, message: '请输入文号', trigger: 'blur'},
                        { validator: validateSymbol, trigger: "blur"}],
                },
                supervision_rules: {
                    supervisorAmount: [{required: false, message: '请输入金额', trigger: 'blur'},
                        { validator: doubleValidate, trigger: "blur"}],
                    supervisorDocument: [{required: false, message: '请输入文号', trigger: 'blur'},
                        { validator: validateSymbol, trigger: "blur"}],
                },
                cost_rules: {
                    costAmount: [{required: false, message: '请输入金额', trigger: 'blur'},
                        { validator: doubleValidate, trigger: "blur"}],
                    costDocument: [{required: false, message: '请输入文号', trigger: 'blur'},
                        { validator: validateSymbol, trigger: "blur"}],
                },
                tenderAgent_rules: {
                    agentAmount: [{required: false, message: '请输入金额', trigger: 'blur'},
                        { validator: doubleValidate, trigger: "blur"}],
                    agentDocument: [{required: false, message: '请输入文号', trigger: 'blur'},
                        { validator: validateSymbol, trigger: "blur"}],
                },
                construction_rules: {
                    constructionAmount: [{required: false, message: '请输入金额', trigger: 'blur'},
                        { validator: doubleValidate, trigger: "blur"}],
                    constructionDocument: [{required: false, message: '请输入文号', trigger: 'blur'},
                        { validator: validateSymbol, trigger: "blur"}],
                }
            }
        },
        methods: {
            //打开弹框
            show(item) {
                this.dialogVisible = true
                if (item) {
                    this.isAdd = false
                    this.projectForm.information.projectTenderId = item
                    get(item).then(res => {
                        if (res.data.code === 0 && res.data.data.epcProjectTender !== null) {
                            this.projectForm.information = res.data.data.epcProjectTender
                            this.projectForm.information.projectType = this.getCardTypeValue(res.data.data.epcProjectTender.projectType,this.projectTypes)
                            this.projectForm.designTender = res.data.data.epcProjectTender
                            this.projectForm.supervision = res.data.data.epcProjectTender
                            this.projectForm.cost = res.data.data.epcProjectTender
                            this.projectForm.tenderAgent = res.data.data.epcProjectTender
                            this.projectForm.construction = res.data.data.epcProjectTender
                        } else {
                            this.$message.warning('暂未获取到数据！')
                        }
                    })
                }
            },
            //关闭弹框
            beforeClose(done) {
                this.$emit('beforeClose')
            },
            //取消
            handleCancel() {
                this.$emit('handleClose')
                this.dialogVisible = false
            },
            //保存
            commit() {
                const information = new Promise((resolve, reject) => {
                    this.$refs['information'].validate((valid) => {
                        if (valid) resolve();
                    })
                })
                const designTender = new Promise((resolve, reject) => {
                    this.$refs['designTender'].validate((valid) => {
                        if (valid) resolve();
                    })
                })
                const supervision = new Promise((resolve, reject) => {
                    this.$refs['supervision'].validate((valid) => {
                        if (valid) resolve();
                    })
                })
                const cost = new Promise((resolve, reject) => {
                    this.$refs['cost'].validate((valid) => {
                        if (valid) resolve();
                    })
                })
                const tenderAgent = new Promise((resolve, reject) => {
                    this.$refs['tenderAgent'].validate((valid) => {
                        if (valid) resolve();
                    })
                })
                const construction = new Promise((resolve, reject) => {
                    this.$refs['construction'].validate((valid) => {
                        if (valid) resolve();
                    })
                })
                Promise.all([information, designTender, supervision, cost, tenderAgent, construction]).then(() => {
                    this.registrationForm = {
                        ...this.projectForm.information,
                        ...this.projectForm.designTender,
                        ...this.projectForm.supervision,
                        ...this.projectForm.cost,
                        ...this.projectForm.tenderAgent,
                        ...this.projectForm.construction}
                    this.$refs.tenderInfoUpload.submit();
                })
            },
            //文件上传
            onSuccess(response, file, fileList){
                //文件上传成功，开始保存表单
                if (fileList !== undefined && fileList.length > 0) {
                    if (response.data) {
                        this.registrationForm.projectTenderId = response.data
                        this.saveFormData(response.data)
                    } else {
                        this.err('文件上传失败')
                    }
                } else {
                    this.saveFormData(response.data)
                }
            },
            saveFormData () {
                this.loadAction('数据加载中')
                if (this.isAdd) {
                    save(this.registrationForm).then((rep) => {
                        this.loadClose()
                        this.$message.success("保存成功");
                        this.dialogVisible = false
                        this.$emit('resetList')
                    }).catch((e) => {
                        this.loadClose()
                        this.$message.error("保存失败");
                    })
                } else {
                    update(this.registrationForm).then((rep) => {
                        this.loadClose()
                        this.$message.success("修改成功");
                        this.dialogVisible = false
                        this.$emit('resetList')
                    }).catch((e) => {
                        this.loadClose()
                        this.$message.error("修改失败");
                    });
                }
            },
            //验证文号是否存在
            validateOnly (rule, value, callback) {
                if (rule.field === 'designDocument') {
                    this.symbolType = '1'
                } else if (rule.field === 'supervisorDocument') {
                    this.symbolType = '2'
                } else if (rule.field === 'costDocument') {
                    this.symbolType = '3'
                } else if (rule.field === 'agentDocument') {
                    this.symbolType = '4'
                } else if (rule.field === 'constructionDocument') {
                    this.symbolType = '5'
                }
                validateCode({ "projectId": this.projectForm.information.projectId, "vType": this.symbolType, "id": this.projectForm.information.projectTenderId, "code": value }).then(rep => {
                    let vr = rep.data.data
                    if (vr === 0) {
                        return callback();
                    } else {
                        return callback(new Error("文号不能重复"));
                    }
                })
            },
            //选择工程名称
            handleClickProjectName() {
                const dictVal_unitType =  (row, column, cellValue) => {
                    if (this.projectTypes.length === 0) return '';
                    let type = this.projectTypes.find(item => item.value == cellValue)
                    return type ? type.label: ''
                };
                this.chooseDialogAttrs = {
                    title: '选择工程',
                    placeholder: '请输入工程名称',
                    url: '/api/epcprojecttender/queryProject',
                    primaryKey: 'projectName',
                    showData: [
                        { prop: 'projectName', label: '工程名称', width: '200', align: 'center'},
                        { prop: 'projectAddress', label: '工程地址', align: 'center'},
                        { prop: 'projectType', label: '工程类型', align: 'center', formatter: dictVal_unitType},
                        { prop: 'agentContact', label: '单位联系人', align: 'center'},
                        { prop: 'agentPhone', label: '联系电话', align: 'center'}
                    ]
                }
                this.$nextTick(() => {
                    this.$refs.chooseDialog.show()
                })
            },

            //工程名称确定
            handleClickAdd(item) {
                if (this.projectForm.information.projectName) {
                    this.$confirm('一次只能添加一条数据，该操作将覆盖上条数据,是否继续?', '提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        this.projectForm.information.projectName = item.projectName
                        this.projectForm.information.projectAddress = item.projectAddress
                        this.projectForm.information.projectId = item.projectId
                        this.projectForm.information.projectSetupId = item.projectSetupId
                        this.projectForm.information.projectType = this.getCardTypeValue(item.projectType,this.projectTypes)
                        this.$message.success('添加成功！')
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        })
                    })
                } else {
                    this.projectForm.information.projectName = item.projectName
                    this.projectForm.information.projectAddress = item.projectAddress
                    this.projectForm.information.projectId = item.projectId
                    this.projectForm.information.projectSetupId = item.projectSetupId
                    this.projectForm.information.projectType = this.getCardTypeValue(item.projectType,this.projectTypes)
                    this.$message.success('添加成功！')
                }
            },
            //对应value取label
            getCardTypeValue(num, sum){
                let arr = sum.filter(e=>e.value === num)
                if (arr.length > 0) {
                    return arr[0].label
                } else {
                    return num
                }
            }
        }
    }
</script>

<style scoped lang='scss'>
    @include formWrap(4);
    .handling-opinions {
        padding: 20px;
    }
</style>
